<template>
  <div class="article-comments">
    <!-- 评论列表 -->
    <van-list
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
<van-cell
        v-for="item in list"
        :key="item.com_id.toString()"
        >
        <van-image
          slot="icon"
          round
          width="30"
          height="30"
          style="margin-right: 10px;"
          :src="item.aut_photo"
        />
        <span style="color: #466b9d;" slot="title">{{item.aut_name}}</span>
        <div slot="label">
          <p style="color: #363636;">{{item.content}}</p>
          <p>
            <span style="margin-right: 10px;">{{item.pubdate | relativeTime }}</span>
            <van-button size="mini" type="default">回复</van-button>
          </p>
        </div>
        <van-icon slot="right-icon" name="like-o" />
      </van-cell>
    </van-list>
    <!-- 评论列表 -->

<!-- 发布评论 -->
    <van-cell-group class="publish-wrap">
      <van-field
        clearable
        placeholder="请输入评论内容"
        v-model.trim="content"
      >
        <van-button slot="button" size="mini" type="info" @click="hAddComment">发布</van-button>
      </van-field>
    </van-cell-group>
    <!-- /发布评论 -->
  </div>
</template>

<script>
import { addComment, getComment } from '../../api/comment.js'
export default {
  name: 'comment',
  data () {
    return {
      list: [], // 评论列表
      loading: false, // 上拉加载状态
      finished: false, // 是否加载结束
      content: '', // 评论内容
      offset: null // 获取评论数据的偏移量，值为评论id，表示从此id的数据向后取，不传表示从第一页开始读取数据
    }
  },
  props: {
    articleId: {
      require: true
    }
  },
  methods: {
    // 获取评论数据加渲染
    async onLoad () {
      try {
        // 1. 发请求
        const res = await getComment(this.articleId, this.offset)
        console.log('12312', res)
        // 2. 把请求的结果追加到list
        const arr = res.data.data.results
        this.list.push(...arr)
        // 3. 手动取消loading
        this.loading = false
        // 4. 判断是否全部加载完成 finished
        // this.finished = !arr.length
        if (arr.length === 0) {
          this.finished = true
        }
        // 5. 更新offset
        this.offset = res.data.data.last_id
      } catch (error) {
        this.$toast('获取评论失败')
        this.loading = false
      }
    },
    // 发布评论
    async hAddComment () {
      try {
        const res = await addComment(this.articleId, this.content)
        console.log(res)
        this.list.unshift(res.data.data.new_obj)
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

<style lang="less" scoped>
// 发表评论的区域是固定在下端的
.publish-wrap {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
}
// 给发表评论区空出地方
.van-list {
  margin-bottom: 45px;
}
</style>
